namespace umbracoUtilities
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
	using System.Xml;
	using System.Text.RegularExpressions;
	using umbraco.cms.businesslogic.member;

	/// <summary>
	///		Summary description for umbSubscribeUnsubscribe.
	/// </summary>
	public partial class umbSubscribeUnsubscribe : System.Web.UI.UserControl
	{

		private string _memberTypeAlias;
		private bool _deleteOnUnsubscribe = false;
		private string _layoutXslt;
		private string _header = "";
		private string _body = "";
		private string _memberGroup;
		private XmlDocument xd = new XmlDocument();

		public string header
		{
			set {_header = value;}
		}
		public string body
		{
			set {_body = value;}
		}
		public string layoutXslt 
		{
			set {_layoutXslt = value;}
		}
		public string memberTypeAlias 
		{
			set {_memberTypeAlias = value;}
		}
		public bool deleteOnUnsubscribe 
		{
			set {_deleteOnUnsubscribe = value;}
		}
		public string memberGroup 
		{
			set {_memberGroup = value;}
		}

		protected void Page_Load(object sender, System.EventArgs e)
		{
			string memberAction = "";
			bool hasErrors = false;
			string memberName = "";
			string memberEmail = "";
			bool actionDone = false;
			XmlElement xdElement = xd.CreateElement("umbSubscribeUnsubscribe");
			xd.AppendChild(xdElement);

			XmlNode errors = xdElement.AppendChild(umbraco.xmlHelper.addTextNode(xd, "errors", ""));
			XmlNode runtimeErrors = xdElement.AppendChild(umbraco.xmlHelper.addTextNode(xd, "runtimeErrors", ""));
			xdElement.AppendChild(umbraco.xmlHelper.addCDataNode(xd, "header", _header));
			xdElement.AppendChild(umbraco.xmlHelper.addCDataNode(xd, "body", _body));

			// Maybe create member
			if (Request["umbSubscribeMemberAction"] != null) 
			{
				if (Request["umbSubscribeMemberAction"] == "subscribe") 
				{

					// Default name is the email adress
					memberEmail = Request["umbSubscribeEmail"];
					memberName = memberEmail;

					// Validate
					if (memberEmail == "") 
					{
						hasErrors = true;
						errors.AppendChild(errors.AppendChild(umbraco.xmlHelper.addTextNode(xd, "error", "emailEmpty")));
					}
					else 
					{
						Regex r;
						r = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
							RegexOptions.IgnoreCase|RegexOptions.Compiled);
						if (!r.IsMatch(memberEmail)) 
						{
							hasErrors = true;
							errors.AppendChild(errors.AppendChild(umbraco.xmlHelper.addTextNode(xd, "error", "emailInvalid")));
						} 
						else 
						{
							// Check for email-adress
							Member m = Member.GetMemberFromEmail(memberEmail);
							if (m != null) 
							{
								MemberGroup mg = MemberGroup.GetByName(_memberGroup);
								if (mg != null) 
								{
									if (m.Groups != null && !m.Groups.ContainsKey(mg.Id))
									{
										m.AddGroup(mg.Id);
										actionDone = true;
										memberAction = "subscribe";
									}
									else 
									{
										hasErrors = true;
										errors.AppendChild(errors.AppendChild(umbraco.xmlHelper.addTextNode(xd, "error", "emailExists")));
									}
								} 
								else 
								{
									hasErrors = true;
									errors.AppendChild(errors.AppendChild(umbraco.xmlHelper.addTextNode(xd, "error", "MemberGroup '" + _memberGroup + "' not found")));
								}
							}
						}
					}
					

					// Check for name
					if (Request["umbSubscribeName"] != null) 
					{
						if (Request["umbSubscribeName"].Trim() == "") 
						{
							memberName = Request["umbSubscribeName"].Trim();
							hasErrors = true;
							errors.AppendChild(errors.AppendChild(umbraco.xmlHelper.addTextNode(xd, "error", "nameEmpty")));
						} 
						else
							memberName = Request["umbSubscribeName"].Trim();
					}


					if (!hasErrors && !actionDone) 
					{
						// Create member
						try 
						{
							MemberType mt = new MemberType(MemberType.GetByAlias(_memberTypeAlias).Id);
							Trace.Write("umbSubscribeUnsubscribe", "MemberName: '" + memberName + "', MemberEmail: '" + memberEmail + "'");
							Member m = Member.MakeNew(memberName, memberEmail, mt, new umbraco.BusinessLogic.User(0));

							// Add to group
							MemberGroup mg = MemberGroup.GetByName(_memberGroup);
							m.AddGroup(mg.Id);

							memberAction = "created";
						} 
						catch (Exception eCreate)
						{
							runtimeErrors.AppendChild(umbraco.xmlHelper.addTextNode(xd, "runtimeError", "Error creating member: " + eCreate.ToString()));
						}

					}
				} 
				else if (Request["umbSubscribeMemberAction"] == "unsubscribe") 
				{
					// Find member
					if (Request["umbSubscribeEmail"] != "") 
					{
						Member m = Member.GetMemberFromEmail(Request["umbSubscribeEmail"]);
						if (m != null) 
						{
							if (_deleteOnUnsubscribe) 
							{
								m.delete();
								memberAction = "deleted";
							} 
							else 
							{
								try 
								{
									MemberGroup mg = MemberGroup.GetByName(_memberGroup);
									m.RemoveGroup(mg.Id);

									memberAction = "unsubscribe";
								} 
								catch 
								{
									runtimeErrors.AppendChild(umbraco.xmlHelper.addTextNode(xd, "runtimeError", "Membergroup '" + _memberGroup + "' does not exists"));
								}
							}
						} 
						else 
						{
							errors.AppendChild(umbraco.xmlHelper.addTextNode(xd, "error", "memberNotFound"));
						}
					} else 
						errors.AppendChild(umbraco.xmlHelper.addTextNode(xd, "error", "emailEmpty"));
				}
			}
			
			// Add name and email to xml document
			xdElement.AppendChild(umbraco.xmlHelper.addCDataNode(xd, "name", memberName));
			xdElement.AppendChild(umbraco.xmlHelper.addCDataNode(xd, "email", memberEmail));

			xdElement.AppendChild(umbraco.xmlHelper.addTextNode(xd, "action", memberAction));
			Xml1.TransformSource = umbraco.GlobalSettings.Path + "/../xslt/" + _layoutXslt;
			Xml1.Document = xd;
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{

		}
		#endregion
	}
}
